<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <div class="filter-container">
        <el-input
          v-model="listQuery.keywords"
          placeholder="请输入关键词"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="加载中..."
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column
          label="用户头像"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-avatar :size="40" :src="scope.row.avatar">
              {{ scope.row.userName?.charAt(0) }}
            </el-avatar>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="userName"
          label="姓名"
          align="center"
        />

        <el-table-column
          prop="phone"
          label="联系电话"
          align="center"
        />

        <el-table-column
          prop="address"
          label="居住地址"
          align="center"
        />
        
        <el-table-column
          prop="type"
          label="身份"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :type="getRoleType(scope.row.type)"
              size="medium"
            >
              {{ formatRole(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
          width="230"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="listQuery.limit"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { getGuanliFuZerenAll, deleteUser } from '@/api/user'

// 角色映射常量
const ROLE_MAPPINGS = {
  'admin': {
    label: 'admin',
    type: 'danger'
  },
  'teacher': {
    label: 'teacher',
    type: 'warning'
  },
  'student': {
    label: 'student',
    type: 'success'
  }
}

export default {
  name: 'UserList',
  
  data() {
    return {
      list: [], // 用户列表数据
      total: 0, // 总条数
      listLoading: true, // 加载状态
      listQuery: {
        page: 1, // 当前页码
        limit: 10, // 每页条数
        keywords: '' // 搜索关键词
      }
    }
  },

  created() {
    this.fetchData()
  },

  methods: {
    // 获取数据
    async fetchData() {
      this.listLoading = true
      try {
        const res = await getGuanliFuZerenAll({
          pageNum: this.listQuery.page,
          pageSize: this.listQuery.limit,
          keywords: this.listQuery.keywords
        })
        
        if (res.code === 200) {
          // 确保返回的数据格式正确
          this.list = Array.isArray(res.data) ? res.data : []
          this.total = res.total || this.list.length
        } else {
          this.$message.error(res.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.listLoading = false
      }
    },

    // 格式化角色显示
    formatRole(type) {
      return ROLE_MAPPINGS[type]?.label || type || '未知身份'
    },

    // 获取角色对应的标签类型
    getRoleType(type) {
      return ROLE_MAPPINGS[type]?.type || 'info'
    },

    // 处理搜索
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },

    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },

    // 处理页码变化
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },

    // 处理编辑
    handleEdit(row) {
      this.$router.push(`/user/edit/${row.id}`)
    },

    // 处理删除
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await deleteUser(row.id)
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.fetchData()
        } else {
          this.$message.error(res.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 10px;
  .filter-item {
    margin-right: 10px;
  }
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>

